package com.googlecode.tidej.client.editor;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.googlecode.tidej.shared.model.Artifact;

public class DocumentationEditor extends Composite {

  FlowPanel panel = new FlowPanel();
  TextArea textArea = new TextArea();
  Artifact artifact;
  Label label = new Label();
  Anchor documentationLink = new Anchor();

  
  public DocumentationEditor() {
    // TextBox margin
    panel.getElement().getStyle().setMargin(2, Unit.PX);
    Style style = textArea.getElement().getStyle();
    // Needed for width:100%
    style.setProperty("boxSizing", "border-box");
    style.setProperty("WebkitBoxSizing", "border-box");
    style.setProperty("MozBoxSizing", "border-box");
    style.setProperty("overflow", "auto");
    style.setProperty("resize", "vertical");
    style.setProperty("width", "100%");
 //   style.setProperty("minHeight", "26px");
    // TextBox padding
    style.setProperty("padding", "5px 4px");
    panel.add(textArea);
    panel.add(label);
    panel.add(documentationLink);
    initWidget(panel);
  }
  
  
  public void setArtifactAndResize(Artifact artifact, boolean readOnly) {
    this.artifact = artifact;
    String text = artifact.getDocumentation();
    if (text == null) {
      text = "";
    }
    String docUrl = artifact.getLibrary() == null ? null : 
        artifact.getLibrary().getDocumentationUrl(artifact);
    if (readOnly) {
      label.setText(text.length() == 0 && docUrl == null ? "n/a" : text);
    } else {
      int count = text.split("\n").length;
      textArea.setHeight((count * 15 + 15) + "px");
      textArea.setText(text);
    }
    textArea.setVisible(!readOnly);
    label.setVisible(readOnly);
    
    if (docUrl != null) {
      documentationLink.setVisible(true);
      documentationLink.setHref(docUrl);
      documentationLink.setText(docUrl);
      documentationLink.setTarget(artifact.getLibrary().getName() + "_doc");
    } else {
      documentationLink.setVisible(false);
    }
    
  }
  
  public boolean checkModifications() {
    if (!textArea.isVisible() || 
        textArea.getText().equals(artifact.getDocumentation())) {
      return false;
    }
    artifact.setDocumentation(textArea.getText());
    return true;
  }
  
}
